package com.ts.proj.json;


import com.ts.base.controller.BaseController;
import com.ts.common.constant.InsUpdDelFlagConstant;
import com.ts.proj.entity.FinanceEntity;
import com.ts.proj.entity.ProjectEntity;
import com.ts.proj.entity.excelEntity.FinanceEntityExcel;
import com.ts.proj.entity.SystemUserEntity;
import com.ts.proj.service.FinanceService;
import com.ts.common.constant.ConsoleConstant;
import com.ts.proj.service.ProjectService;
import com.ts.util.PageData;
import com.ts.util.StringsUtil;
import com.ts.util.DateUtil;
import com.ts.util.EasyPoiUtil;
import com.ts.util.EntityAttributeUtil;
import com.ts.util.*;
import com.ts.vo.FinanceVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import java.util.*;
import javax.servlet.http.HttpServletResponse;



import javax.servlet.http.HttpSession;
import com.ts.proj.entity.SystemUserEntity;
import com.ts.util.JsonUtils;
import com.ts.common.constant.ConsoleConstant;

//说明 字符串：Finance，作为替换字符串 LOWERFinance

@RestController
public class FinanceJson extends BaseController{

    @Autowired
    private FinanceService financeService;
    @Autowired
    private ProjectService projectService;

    /**
     * 显示list
     * @param page
     * @param size
     * @return
     * 查询财务表
     */
    @RequestMapping(value = "/finance-list/{page}/{size}")
    public Map<String,Object> financeList(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
	
		HttpSession session = this.getRequest().getSession();
        SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);
	
        PageData pageData = this.getPageData();
        pageData.put("deleteFlag", "N");

		//用户权限
        if(user.getPowerLevel().equals("0")){
            pageData.put("userId", user.getId());
        }
        pageData.put("belongTo", user.getBelongTo());
        if(null != pageData.get("pro_Id") && "".equals(pageData.getString("pro_Id"))){
            pageData.put("pro_Id",pageData.getString("pro_Id"));
        }
        long count = financeService.count(pageData);
        List<FinanceEntity> finances = financeService.findAll(pageData,page-1,size);
        pageData.put("total",count);
        pageData.put("rows", finances);
        return pageData;
    }

    /**
     * 常量增删改
     * @return
     */
    @RequestMapping(value = "/finance-ins-upd-del/{id}")
    public Object logCreateUpdate(@PathVariable("id") String id){ 
	
		FinanceEntity finance = financeService.findById(Integer.valueOf(id));
        PageData pageData = this.getPageData();

        List<String> strings = EntityAttributeUtil.entityAttribute(FinanceEntity.class);
		 SystemUserEntity systemUserEntity = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);

        for(String attr :strings){
            //字段信息维护
            if(null!=pageData.get(attr)&&!"".equals(pageData.get(attr).toString())){
                //目前只能手动添加，这里添加所需要增加和修改的字段
                try {
                    Method[] methods = FinanceEntity.class.getDeclaredMethods();
                    for(int i=0;i<methods.length;i++){
                        Method method = methods[i];
                        Class<?>[] returnType = method.getParameterTypes();
                        if(method.getName().contains(StringsUtil.upperCase(attr))&&!method.getName().contains("get")){
                            if (returnType[0].getName().equals("java.lang.Integer")){
                                method.invoke(finance, Integer.valueOf(pageData.getString(attr)));
                            }
                            else{
                                method.invoke(finance, pageData.getString(attr));
                            }
                        }
						if(method.getName().equals("setUserId")){
                            finance.setUserId(systemUserEntity.getId());
                        }
                        if(method.getName().equals("setBelongTo")){
                            finance.setBelongTo(systemUserEntity.getBelongTo());
                        }
						if(method.getName().equals("setPowerLevel")){
                            finance.setPowerLevel(systemUserEntity.getPowerLevel());
                        }

                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }  catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }	
        financeService.save(finance);
        return null;
    } 
	@RequestMapping("/finance-download")
    public void export(HttpServletResponse response){
        PageData param = new PageData();
        param.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<FinanceEntity> entitys = financeService.findAll(param);
        List<FinanceEntityExcel> excelEntities = new ArrayList<>();
        for(FinanceEntity tempEntity :entitys){            
            FinanceEntityExcel excel = new CopyObjectEntity2EntityExcel<FinanceEntityExcel, FinanceEntity>().copy(FinanceEntityExcel.class,FinanceEntity.class,tempEntity);
            excelEntities.add(excel);
        }
        EasyPoiUtil.exportExcel(excelEntities,"","",FinanceEntityExcel.class, DateUtil.getID()+".xls",response);
    }
    /**
     * 将id转化为name
     *
     */

    @RequestMapping("/pro_Id_Name/{id}")
    public ProjectEntity proIdName(@PathVariable("id") String id){
        ProjectEntity projectEntity = projectService.findById(Integer.valueOf(id.toString()));
        return projectEntity;
    }


    @RequestMapping("/idConversionName")
    public Object idConversionName(){
        List<ProjectEntity> projectEntityList = projectService.findAll();
        List<PageData> pageDataList = new ArrayList<>();
        for(ProjectEntity p : projectEntityList){
            PageData pageData = new PageData();
            pageData.put("id",p.getId());
            pageData.put("name",p.getProName());
            pageDataList.add(pageData);
        }
        return pageDataList;
    }

    /**
     *
     * 根据项目名称模糊查询
     * 级联查询
     * */
    @RequestMapping("/search-proName/{page}/{size}")
    public Object searchByProName(@PathVariable String page , @PathVariable String size) {

        List<PageData> financeEntityList = null;
        PageData pageData = this.getPageData();
        String name = "";
        if (null != pageData.get("pro_name_like") && !"".equals(pageData.getString("pro_name_like"))) {
            name = pageData.get("pro_name_like").toString();
        }
        financeEntityList = financeService.findProjectAndFinanceList(name);
        List<FinanceEntity> financeEntitiesList  = new ArrayList<>();
        for(PageData pageData1 : financeEntityList){
            FinanceEntity financeEntity = MapObjUtil.map2Object(pageData1, FinanceEntity.class);
            financeEntity.setProjectEntity(projectService.findById(financeEntity.getProId()));
            financeEntitiesList.add(financeEntity);
        }


        return financeEntitiesList ;
    }
}